import axios from 'axios'
import querystring from 'querystring'
import {Promise} from 'es6-promise'
import config from '../config'
import {Notification} from 'element-ui'

window.Promise = Promise // 解决ie找不到Promise

axios.defaults.baseURL = config.baseURL

axios.defaults.withCredentials = true // 跨域带sension

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'

// axios.defaults.xsrfCookieName = '后台给cookie字段'  //获取cookie

axios.defaults.transformRequest = function (data) {
  return querystring.stringify(data)
}
axios.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    return Promise.reject(error)   // 返回接口返回的错误信息
  }
)

/**
 * 过滤空值的属性
 * @param obj
 * @constructor
 */
function FilterData(obj) {
  for (var key in obj) {
    if (obj[key] === null || obj[key] === '') {
      delete obj[key]
    }
  }
}

export default function ajax(config) {
  FilterData(config.params) // 过滤空属性;
  FilterData(config.data)  // 过滤空属性;
  return axios(config)
    .then(res => {
      if (res.responseCode === 200) {
        return res
      }else if(res.responseCode === 401){
        this.$router.push({name: 'login'})
      }else if(res.responseCode === 408){
        this.$message.error(res.message);
        this.$router.push({name: 'login'})
      }else if(res.responseCode === 412){
        return res
      } else {
        this.$message.error(res.message);
        return res
      }
    })
    .catch(err => {
        if (err.toString().indexOf('404') !== -1) {
          Notification({
            type: 'error',
            title: '404',
            message: '没有找到相应接口'
          })
        } else if (err.toString().indexOf('403') !== -1) {
          Notification({
            type: 'error',
            message: '无权访问'
          })
        } else {
          Notification({
            type: 'error',
            message: '网络请求失败'
          })
        }
      // return err;
      }
    )
}
